﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using SdmxMl.Structure;
using SdmxMl.Common;

namespace SdmxMl.UC
{
    public partial class UcHierarchyClRef : UserControl, IUrnSelect 
    {
        private CodelistRefTypeList clrList;
        private CodelistRefType clr;
        private DataTable tb;
        private BindingManagerBase bm = null;
        private bool _isFinal;

        private bool inBinding;

        public UcHierarchyClRef()
        {
            InitializeComponent();
        }

        public bool BindFromNode(TreeNode node, bool isFinal)
        {
            _isFinal = isFinal;
            if (node != null)
            {
                clr = null;
                clrList = node.Tag as CodelistRefTypeList;
            }
            BindToControls();

            return Visible;
        }

        public bool UpdateNodeTag(TreeNode node)
        {
            if (node != null)
                BindFromControls();

            return false; // true on error
        }
        private void BindToControls()
        {
            inBinding = true;
            if (clrList != null)
            {
                Visible = true;
                
                tb = clrList.GetTableRepresentation();
                dataGridView.DataSource = tb;
                dataGridView.Enabled = !_isFinal;
                if (clrList.Count > 0)
                    BindRow(clrList[0]);
                EnableGrigButtons(true);

            }
            else
                Visible = false;

            ucCodelistRef.Enabled = !_isFinal;
            textBoxAlias.Enabled = !_isFinal;
            textBoxUrn.Enabled = !_isFinal;

            inBinding = false;
        }

        protected bool BindFromControls()
        {
            bool err = false;
            if (clrList != null)
            {            
                UpdateRow();
            }

            return err;
        }


        public void BindRow(CodelistRefType rowClr)
        {
            if (clr != rowClr)
            {

                clr = rowClr;
                if (clr != null)
                {
                    ucCodelistRef.BindRef(clr);

                    textBoxAlias.Text = clr.Alias;
                    textBoxUrn.Text = clr.Urn;
                }
                else
                {
                    ucCodelistRef.BindRef(null);

                    textBoxAlias.Text = string.Empty;
                    textBoxUrn.Text = string.Empty;
                }
            }
        }




        /// <summary>Update Grid buttons state</summary>
        /// <param name="enable">If true buttons are enabled</param>
        protected void EnableGrigButtons(bool enable)
        {
            butAdd.Enabled = enable && !_isFinal; ;

            butRemove.Enabled = enable && !_isFinal && clrList != null && clrList.Count > 0 && dataGridView.SelectedCells.Count > 0;
        }

        private void butAdd_Click(object sender, EventArgs e)
        {
            CodelistRefType clr = new CodelistRefType();
            clr.Id = "undefined";
            clrList.Add(clr);
            dataGridView.DataSource = clrList.GetTableRepresentation();
            dataGridView.FirstDisplayedScrollingRowIndex = clrList.Count - 1;
            SelectGridRow(dataGridView, clrList.Count - 1);

            dataGridView_SelectionChanged(this, EventArgs.Empty);
            EnableGrigButtons(true);
        }

        

        private void butRemove_Click(object sender, EventArgs e)
        {
            bm = dataGridView.BindingContext[dataGridView.DataSource, dataGridView.DataMember];
            if (bm.Count > 0)
            {
                DataRow findRow = ((DataRowView)bm.Current).Row;
                if (findRow != null)
                {
                    int index = (dataGridView.DataSource as DataTable).Rows.IndexOf(findRow);
                    clrList.RemoveAt(index);
                    dataGridView.DataSource = clrList.GetTableRepresentation();
                    index = Math.Min(clrList.Count - 1, index);
                    SelectGridRow(dataGridView, index);
                    EnableGrigButtons(true);
                }
                if (clrList.Count == 0)
                    BindRow(null);
                else
                    dataGridView_SelectionChanged(this, EventArgs.Empty);


            }

        }

        private void SelectGridRow(DataGridView dgv, int index)
        {
            if (index < 0)
                return;

            if (dgv.CurrentCell != null)
                dgv.CurrentCell.Selected = false;
            dgv.Rows[index].Cells[0].Selected = true;
            dgv.CurrentCell = dgv.SelectedCells[0];

        }

        private void dataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (inBinding)
                return;

            // dataGridView.so = SortOrder.None;
            UpdateRow();
            bm = dataGridView.BindingContext[dataGridView.DataSource, dataGridView.DataMember];
            if (bm.Count > 0)
            {
                DataRow findRow = ((DataRowView)bm.Current).Row;
                if (findRow != null)
                {
                    int index = (dataGridView.DataSource as DataTable).Rows.IndexOf(findRow);
                    CodelistRefType rowBd = null;
                    if (index >= 0 && index < clrList.Count)
                    {
                        rowBd = clrList[index];
                        BindRow(rowBd);
                    }
                }
            }
             

        }
        public void UpdateRow()
        {
            if (clr != null)
            {
                DataTable tb = dataGridView.DataSource as DataTable;
                dataGridView.EndEdit();
                int rowIndex = clrList.IndexOf(clr);
                if (rowIndex >= 0 && tb != null)
                {
                    if (tb.Rows.Count <= rowIndex)
                    {
                    }
                    else
                    {
                        // Update row
                        clr.Alias = textBoxAlias.Text;
                        clr.Urn = textBoxUrn.Text;
                        tb.Rows[rowIndex].ItemArray = clrList.GetRowObjects(clrList[rowIndex]).ToArray();
                        tb.Rows[rowIndex].AcceptChanges();
                    }
                }
            }
        }


        #region IUrnSelect Members

        public void SelectItem(UrnParser up)
        {
            if (up != null && up.ArType == SdmxMl.Manager.SdmxArtefactType.HierarchicalCodelists &&
                dataGridView.DataSource != null)
            {
                // Try to locate refered codelist
                int ndx = 0;
                foreach (CodelistRefType clrt in clrList)
                {
                    if (clrt.Alias == up.SubTypeId)
                    {
                        dataGridView.DataSource = clrList.GetTableRepresentation();
                        dataGridView.FirstDisplayedScrollingRowIndex = clrList.Count - 1;
                        SelectGridRow(dataGridView, ndx);
                        break;
                    }
                    ++ndx;
                }

            }
        }

        #endregion
    }
}
